<?php
/**
 * Created by PhpStorm.
 * User: Marmot
 * Date: 2018/5/7
 * Time: 15:06
 */
namespace app\admin\controller;
use think\Controller;
use app\admin\model\Common;
use app\facade\Power;
use think\Db;
use Qiniu\Storage\UploadManager;
use Qiniu\Auth;

//控制器基类，一般用来做登陆验证/功能权限验证等，不能直接访问
class Base extends Controller {
    protected function initialize(){
        //登陆判断
        if(!session('?login')){
            $this->success('登陆过期，请重新登陆','login/index');
        }

        //左侧导航
        $common = new Common();
        $nav = $common->get_nav(Power::get_auth_fun_id_arr());
        $this->assign('nav_arr',$nav);
        $this->assign('user', session('login'));

    }

    public function getConfig()
    {
        $config = Db::table('d_config')->select();
        $d = [];
        foreach ($config as $v) {
            $d[$v['key']] = $v['value'];
        }
        return $d;
    }

    public function editConfig ()
    {
        $datas = input('post.');
        foreach ($datas as $key => $value) {
            Db::table('d_config')->where('key', $key)->update(['value'=>$value]);
        }
        $images = ['COMPANY_IMAGE'];
        foreach ($images as $v) {
            $url = $this->upload2($v);
            if ($url != 999) {
                Db::table('d_config')->where('key', $v)->update(['value'=>$url]);
            }
        }
    }



    //文件上传
    public function upload2($field){
        // 获取表单上传文件 例如上传了001.jpg
        $file = request()->file($field);
        // 移动到框架应用根目录/public/uploads/ 目录下
        if($file){
            $info = $file->move($_SERVER['DOCUMENT_ROOT'].'/uploads');
            if($info){
                // 成功上传后 获取上传信息
                $urls =  $info->getFilename();
                $url = '/uploads/'.date('Ymd').'/'.$urls;
                return $url;
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }else{
            return 999;
        }
    }

    //文件上传
    public function uploadz(){
        $image = $_POST['base64'];
        $file = $this->base64_image_content($image, $_SERVER["DOCUMENT_ROOT"].'/uploads');
        return json_encode(['status'=>1, 'url'=>$file]);
    }

    /**
     * [将Base64图片转换为本地图片并保存]
     * @E-mial wuliqiang_aa@163.com
     * @TIME   2017-04-07
     * @WEB    http://blog.iinu.com.cn
     * @param  [Base64] $base64_image_content [要保存的Base64]
     * @param  [目录] $path [要保存的路径]
     */
    function base64_image_content($base64_image_content,$path)
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)) {
            $type = $result[2];
            $new_file = date('Ymd', time()) . "/";

            if (!file_exists($new_file)) {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                mkdir($new_file, 0700);
            }
            $new_file = $new_file . time() . ".{$type}";
            $ret = $this->qiniu($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)));

            if (isset($ret[0]['key'])) {
                return 'http://img.nuojsteel.com/'.$ret[0]['key'];
            } else {
                return false;
            }
        } else {
            return false;
        }
    }


    public function qiniu($new_file, $content)
    {
        $accessKey = 'Uk5gtXIE_dFT_RQnGq3QOKXRAb2STM2mCz16ob33';
        $secretKey = 'NpwsjwkSsNiSSrKDgMonnF7ZAOku90d3I8cffwOh';
        $bucketName = 'nuojsteel';
        $upManager = new UploadManager();
        $auth = new Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucketName);
        return $upManager->put($token, $new_file, $content);
    }

    }